<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="isAll" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>

      <ShoppingCar
        :goodList="goodList"
        @cutNum="cutNumFn"
        @addNum="addNumFn"
        @chooseAll="chooseAllFn"
        @choose="chooseFn"
        @delItem="delItemFn"
      ></ShoppingCar>
      <tfoot>
        <TotalPrice :totalPrice="totalPrice" />
      </tfoot>
    </table>
  </div>
</template>

<script>
import ShoppingCar from './components/ShoppingCar.vue'
import TotalPrice from './components/TotalPrice.vue'
export default {
  data() {
    return {
      goodList: [
        {
          name: '诸葛亮',
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: '蔡文姬',
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: '妲己',
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: '鲁班',
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    }
  },
  components: {
    ShoppingCar,
    TotalPrice,
  },
  methods: {
    cutNumFn(index) {
      // console.log('cutNum触发了', index)
      if (this.goodList[index].num === 0) {
        return alert('数量不能少于0')
      }
      this.goodList[index].num--
    },
    addNumFn(index) {
      // console.log('addNum触发了', index)
      this.goodList[index].num++
    },
    chooseAllFn(val) {
      this.goodList.forEach((v) => (v.checked = val))
    },
    chooseFn(index) {
      // console.log('触发了', index)
      this.goodList[index].checked = !this.goodList[index].checked
    },
    delItemFn(index) {
      this.goodList.splice(index, 1)
    },
  },
  computed: {
    isAll: {
      get() {
        return this.goodList.every((v) => v.checked)
      },
      set(val) {
        // console.log(val)
        // this.$emit('chooseAll', val)
        this.goodList.forEach((v) => (v.checked = val))
      },
    },
    totalPrice() {
      // console.log(1)
      return this.goodList.reduce((sum, item) => {
        if (item.checked) return sum + item.price * item.num
        return sum
      }, 0)
    },
  },
}
</script>

<style>
tfoot {
  text-align: center;
}
</style>
